﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectTool.Models;
using System.Data.Entity;
using ProjectTool.Lib;


namespace ProjectTool.Controllers
{
  public class ProjectsController : Controller
  {
    //
    // GET: /Projects/
    
    public ActionResult Index()
    {
      using (ProjectEntities dbContext = new ProjectEntities())
      {
        return View(dbContext.Projects.ToList());
      }
    }

    //
    // GET: /Projects/Details/5

    public ActionResult Details(int proj_id)
    {
      using (var db = new ProjectEntities())
      {
        var proj = db.Projects.Include(c => c.proj_user_link.Select(b => b.proj_user)).ToList();
        return View(proj.SingleOrDefault(p => p.proj_id == proj_id));
      }
    }

    //
    // GET: /Projects/Create
    [CustomAuthorize()]
    public ActionResult Create()
    {
      return View();
    }

    //
    // POST: /Projects/Create

    [HttpPost]
    [CustomAuthorize()]
    public ActionResult Create(Project proj)
    {
      try
      {
        using (var db = new ProjectEntities())
        {
          db.Projects.Add(proj);
          db.SaveChanges();
        }

        return RedirectToAction("Index");
      }
      catch
      {
        return View();
      }
    }

    //
    // GET: /Projects/Edit/5
    [CustomAuthorize()]
    public ActionResult Edit(int proj_id)
    {
      using (var db = new ProjectEntities())
      {
        return View(db.Projects.Find(proj_id));
      }
    }

    //
    // POST: /Projects/Edit/5

    [HttpPost]
    [CustomAuthorize()]
    public ActionResult Edit(int proj_id, Project proj)
    {
      try
      {
        using (var db = new ProjectEntities())
        {
          db.Entry(proj).State = System.Data.EntityState.Modified;
          db.SaveChanges();
        }

        return RedirectToAction("Index");
      }
      catch
      {
        return View();
      }
    }

    //
    // GET: /Projects/Delete/5
    [CustomAuthorize()]
    public ActionResult Delete(int proj_id)
    {
      using (var db = new ProjectEntities())
      {
        return View(db.Projects.Find(proj_id));
      }
    }

    //
    // POST: /Projects/Delete/5

    [HttpPost]
    [CustomAuthorize()]
    public ActionResult Delete(int proj_id, Project proj)
    {
      try
      {
        using (var db = new ProjectEntities())
        {
          db.Entry(proj).State = System.Data.EntityState.Deleted;
          db.SaveChanges();
        }

        return RedirectToAction("Index");
      }
      catch
      {
        return View();
      }
    }
  }
}
